import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:travel/model/tourism.dart';
import 'package:travel/screen/flutter_screenutil.dart';
import 'package:travel/utils/colors.dart';
import 'package:travel/utils/styles.dart';
import 'package:travel/utils/tools.dart';

class ComprehensiveController extends GetxController {
  RxInt tabIndex = 0.obs;

  RxBool isLoading = false.obs;

  RxBool hasNext = true.obs;

  RxInt total = 20.obs;

  RxList<String> tabs = RxList(['智能排序', '最新发布', '最靠近景点']);

  RxList<TourismModel> data = RxList([]);

  final ScrollController scroll = ScrollController();

  @override
  void onInit() {
    super.onInit();
    scroll.addListener(_listener);
    initData();
  }

  void _listener() {
    if (isLoading.isFalse && scroll.position.pixels >= scroll.position.maxScrollExtent) {
      isLoading.value = true;
      loadMoreData();
    }
  }

  void initData() {
    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p0.png',
        describe: '和家人果断在北京续住3天的神仙小院',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p1.png',
        browse: 1.1,
        nickname: '晚风心里吹'));
    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p7.png',
        describe: '人少景美“京西小故宫”修缮五年后惊艳开放',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p8.png',
        browse: 1.3,
        nickname: '唐糖唐来了'));
    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p2.png',
        describe: '北京海拔2000米的木栈道帝都最高观景平台',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p3.png',
        browse: 2.1,
        nickname: '美腻的猫'));
    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p9.png',
        describe: '和家人果断在北京续住3天的神仙小院',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p10.png',
        browse: 1.1,
        nickname: '小沈阳10'));
    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p4.png',
        describe: '北京郊区大自然山景私汤山酒店',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p5.png',
        browse: 1.1,
        nickname: '美美在旅行'));
    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p11.png',
        describe: '人少景美“京西小故宫”修缮五年后惊艳开放',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p12.png',
        browse: 1.7,
        nickname: '美美在旅行'));
    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p6.png',
        describe: '北京周末去哪，找到了人少景美的仙境了！',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p1.png',
        browse: 3.1,
        nickname: '晚风吹心里'));
    data.add(TourismModel(
        imgUrl: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p13.png',
        describe: '秋冬京城小奈良动物园里泡温泉',
        avatar: 'https://cdn7.axureshop.com/demo2023/2251242/images/首页_未登录/p10.png',
        browse: 1.1,
        nickname: '万能夏小姐'));
  }

  @override
  void onClose() {
    super.onClose();
    scroll.removeListener(_listener);
    Get.delete();
  }

  Future<void> loadMoreData() {
    return Future.delayed(const Duration(seconds: 1), () {
      if (total.value > data.length) {
        hasNext.value = true;
        isLoading.value = false;
        initData();
        return;
      }
      hasNext.value = false;
      isLoading.value = false;
    });
  }
}

class ComprehensivePage extends GetView<ComprehensiveController> {
  const ComprehensivePage({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
        builder: (_) {
          return Obx(() => CustomScrollView(
            controller: controller.scroll,
            slivers: [
              SliverPadding(
                padding: EdgeInsets.all(10.w),
                sliver: SliverToBoxAdapter(
                  child: Container(
                    height: 130.h,
                    decoration: BoxDecoration(
                        color: Colors.white, borderRadius: BorderRadius.circular(8.w)),
                    child: Stack(
                      children: [
                        Container(
                          padding: EdgeInsets.all(15.w),
                          alignment: Alignment.centerLeft,
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              ClipRRect(
                                borderRadius: BorderRadius.circular(8.w),
                                child: ToolsUtils.image('result.png', width: 100.w, height: 100.h),
                              ),
                              Expanded(
                                  child: Container(
                                    alignment: Alignment.centerLeft,
                                    padding: EdgeInsets.only(left: 10.w),
                                    child: Column(
                                      children: [
                                        Container(
                                          alignment: Alignment.centerLeft,
                                          child: Text(
                                            '故宫博物馆',
                                            style: StylesUtils.customTextStyle(
                                                color: ColorsUtils.color3333,
                                                fontSize: 16.sp,
                                                fontWeight: FontWeight.w700),
                                          ),
                                        ),
                                        Container(
                                            alignment: Alignment.centerLeft,
                                            margin: EdgeInsets.symmetric(vertical: 10.w),
                                            child: Container(
                                              constraints:
                                              BoxConstraints.tightFor(width: 24.w, height: 18.h),
                                              alignment: Alignment.center,
                                              decoration: BoxDecoration(
                                                  color: ColorsUtils.parseColorFromHexString(
                                                      ColorsUtils.colorF2f2),
                                                  borderRadius: BorderRadius.circular(3.w)),
                                              child: Text(
                                                '5A',
                                                style: StylesUtils.customTextStyle(
                                                    color: ColorsUtils.color6666, fontSize: 12.sp),
                                              ),
                                            )),
                                        Container(
                                          alignment: Alignment.centerLeft,
                                          margin: EdgeInsets.only(bottom: 10.w),
                                          child: Wrap(
                                            spacing: 8.w,
                                            crossAxisAlignment: WrapCrossAlignment.center,
                                            children: [
                                              Text(
                                                '4.8分',
                                                style: StylesUtils.customTextStyle(
                                                    color: ColorsUtils.color3478,
                                                    fontWeight: FontWeight.w700,
                                                    fontSize: 16.sp),
                                              ),
                                              Text(
                                                '127899人评价',
                                                style: StylesUtils.customTextStyle(
                                                    color: ColorsUtils.color7979, fontSize: 12.sp),
                                              )
                                            ],
                                          ),
                                        ),
                                        Container(
                                          alignment: Alignment.centerLeft,
                                          child: Text(
                                            '北京市东城区景山前街4号',
                                            overflow: TextOverflow.ellipsis,
                                            maxLines: 1,
                                            style: StylesUtils.customTextStyle(
                                                color: ColorsUtils.color7979, fontSize: 12.sp),
                                          ),
                                        )
                                      ],
                                    ),
                                  ))
                            ],
                          ),
                        ),
                        Positioned(
                          top: 0,
                          left: 0,
                          width: 50.w,
                          height: 20.h,
                          child: Container(
                            decoration: BoxDecoration(
                                color: ColorsUtils.parseColorFromHexString(ColorsUtils.color3478),
                                borderRadius: BorderRadius.only(
                                    topLeft: Radius.circular(8.w),
                                    bottomRight: Radius.circular(8.w))),
                            alignment: Alignment.center,
                            child: Text(
                              '最相关',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.colorFfff, fontSize: 12.sp),
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              ),
              SliverPersistentHeader(
                  delegate: _TabHeader(
                      child: Container(
                        padding: EdgeInsets.symmetric(horizontal: 10.w),
                        alignment: Alignment.centerLeft,
                        color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF2f2),
                        child: Wrap(
                          spacing: 20.w,
                          crossAxisAlignment: WrapCrossAlignment.center,
                          children: controller.tabs
                              .asMap()
                              .map((index, value) => MapEntry(
                              index,
                              InkWell(
                                onTap: () {
                                  controller.tabIndex.value = index;
                                },
                                child: Text(
                                  value,
                                  style: StylesUtils.customTextStyle(
                                      color: index == controller.tabIndex.value
                                          ? ColorsUtils.color3478
                                          : ColorsUtils.color3333,
                                      fontSize: 13.sp),
                                ),
                              )))
                              .values
                              .toList(),
                        ),
                      )),
                  pinned: true),
              SliverPadding(
                padding: EdgeInsets.symmetric(horizontal: 10.w),
                sliver: SliverGrid(
                  delegate: SliverChildListDelegate(controller.data
                      .map((e) => Column(
                    children: [
                      Container(
                        height: 170.h,
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(8.w),
                                topRight: Radius.circular(8.w)),
                            image: DecorationImage(
                                alignment: Alignment.topLeft,
                                fit: BoxFit.fill,
                                filterQuality: FilterQuality.high,
                                image: NetworkImage(
                                  e.imgUrl,
                                ))),
                      ),
                      Container(
                        margin: EdgeInsets.symmetric(vertical: 8.w),
                        alignment: Alignment.centerLeft,
                        child: Text(
                          e.describe,
                          overflow: TextOverflow.ellipsis,
                          maxLines: 2,
                          style: StylesUtils.customTextStyle(
                            fontWeight: FontWeight.w700,
                            color: ColorsUtils.color3333,
                            lineHeight: 1.5
                          ),
                        ),
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(
                              child: Text.rich(
                                TextSpan(children: [
                                  WidgetSpan(
                                      child: CircleAvatar(
                                        radius: 10,
                                        backgroundImage: NetworkImage(e.avatar),
                                      )),
                                  TextSpan(
                                      text: '  ${e.nickname}',
                                      style: StylesUtils.customTextStyle(
                                          color: ColorsUtils.color6666, fontSize: 13.sp))
                                ]),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              )),
                          Text.rich(TextSpan(children: [
                            WidgetSpan(
                                child: Icon(Icons.remove_red_eye_outlined,
                                    color: ColorsUtils.parseColorFromHexString(
                                        ColorsUtils.color3333),
                                    size: 15.w),
                                alignment: PlaceholderAlignment.middle),
                            TextSpan(
                                text: '${e.browse}万',
                                style: StylesUtils.customTextStyle(
                                    color: ColorsUtils.color6666, fontSize: 13.sp))
                          ]))
                        ],
                      )
                    ],
                  ))
                      .toList()),
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                      crossAxisSpacing: 10.w,
                      mainAxisSpacing: 10.w,
                      childAspectRatio: 0.59),
                ),
              ),
              if (controller.hasNext.isFalse)
                renderBottom()
              else if (controller.isLoading.isTrue)
                renderBottom()
            ],
          ));
        },
        init: Get.put(ComprehensiveController()));
  }

  Widget renderBottom() {
    if (controller.hasNext.isFalse) {
      return SliverToBoxAdapter(
        child: Container(
          padding: const EdgeInsets.symmetric(vertical: 15),
          alignment: Alignment.center,
          child: const Text(
            '已经到底',
            style: TextStyle(
              fontSize: 15,
              color: Color(0xFF333333),
            ),
          ),
        ),
      );
    }
    if (controller.isLoading.isTrue) {
      return SliverToBoxAdapter(
          child: Container(
        padding: const EdgeInsets.symmetric(vertical: 15),
        child: const Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '努力加载中...',
              style: TextStyle(
                fontSize: 15,
                color: Color(0xFF333333),
              ),
            ),
            Padding(padding: EdgeInsets.only(left: 10)),
            SizedBox(
              width: 20,
              height: 20,
              child: CircularProgressIndicator(strokeWidth: 3),
            ),
          ],
        ),
      ));
    }
    return SliverToBoxAdapter(
        child: Container(
      padding: const EdgeInsets.symmetric(vertical: 15),
      alignment: Alignment.center,
      child: const Text(
        '上拉加载更多',
        style: TextStyle(
          fontSize: 15,
          color: Color(0xFF333333),
        ),
      ),
    ));
  }
}

class _TabHeader extends SliverPersistentHeaderDelegate {
  Widget child;

  _TabHeader({required this.child});

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return child;
  }

  @override
  double get maxExtent => 40.h;

  @override
  double get minExtent => 40.h;

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) {
    return this != oldDelegate;
  }
}
